package com.ljx.funchat.common.exception;

import com.ljx.funchat.common.domain.vo.resp.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 方法校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResult<?> methodArgumentNotValidException(MethodArgumentNotValidException e){
        StringBuilder stringBuilder = new StringBuilder();
        for (FieldError fieldError : e.getFieldErrors()) {
            stringBuilder.append(fieldError.getField()).append(fieldError.getDefaultMessage()).append(",");
        }
        log.info("validation parameters error！The reason is:{}", stringBuilder);
        return ApiResult.fail(CommonErrorEnum.PARAM_INVALID.getCode(), stringBuilder.substring(0, stringBuilder.length() - 1));
    }

    /**
     * 最后一道防线
     * @param e
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResult<?> throwable(Throwable e){
        log.info("system exception!the reason is {}", e.getMessage(), e);
        return ApiResult.fail(CommonErrorEnum.SYSTEM_ERROR);
    }

    /**
     * 自定义异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResult<?> businessException(BusinessException e){
        log.info("business exception!the reason is {}", e.getMessage(), e);
        return ApiResult.fail(e.getErrorCode(), e.getErrorMsg());
    }
}
